<template>
  <!-- <div> -->
  <div v-if="activeAudio">

        <audio
          style="display: block; width: 100%;"
          ref="audio"
          :src="activeAudio.audioUrl"
          autoplay ></audio>

        <div class="process-bar">
          <div class="process-lines"
              ref="process"
              @click.stop="onProcess($event.pageX)"
              @touchstart.stop="onProcessTouchStart"
              @touchmove.stop="onProcessTouchMove"
              @touchend.stop="onProcessTouchEnd">
            <div class="total-line"></div>
            <div class="current-line" :style="`width: ${computedProgress}%;`">
              <div class="loading" v-if="state.isLoading"></div>
            </div>
          </div>
          <div class="data">
            <div>{{computedCurrentTime}}</div>
            <div>{{activeAudio.audioDuration}}</div>
          </div>
        </div>

        <div class="control-operation">
          <div class="control-bar">

            <div class="pre-seconds">
              <span class="btn-pre-seconds" @click.stop.prevent="changeCurrentTime(-15)"></span>
            </div>

            <div class="control-core">
              <span
                :class="['btn-play', {isPlaying: state.isPlaying }]"
                @click.stop.prevent="audioToggle">
              </span>
            </div>

            <div class="next-seconds">
              <span class="btn-next-seconds" @click.stop.prevent="changeCurrentTime(15)"></span>
            </div>

          </div>
        </div>

      </div>
  <!-- </div> -->
</template>

<script>
export default {
  props: {
    activeAudio: {
      required: true,
      default: () => null
    }
  },

  data () {
    return {
      zanNum: '',
      stop: false,
      zaned: false,
      audioData: '',
      autoPlay: false,
      state: {
        isPlaying: true, // 播放状态
        isTouching: false, // 用户是否正在连续触摸屏幕
        isLoading: false, // 音频是否因为下一帧缓冲而暂停
        autoPlayed: false, // 是否已经自动播放过
      },
      // playSrc: require('@/assets/images/media-play.svg'),
      // pauseSrc: require('@/assets/images/media-pause.svg'),
      duration: '', // 当前音源播放总时长
      currentTime: '', // 当前音源播放时刻
      currentTimeWatcher: '', // 用于更新当前播放时刻
      currentAudioIndex: 0, // 当前播放音源序号
      currentX: 0, // 当前触摸位置X坐标
      showDialog: false,
      dialogConent: {
        title: ' 抱歉！您未开通“每日听书”VIP<br/> 立即开通VIP畅听全书籍',
        left: '返回',
        right: '开通VIP'
      },
      limitTime: 300,
      computedCurrentAudioIndex: ''
    }
  },

   watch: {
     activeAudio: {
      deep: true,
      handler () {
        // 重置
        //  this.state.isPlaying = true
        // //  this.duration = 0
        //  this.currentTime = 0
        //  this.currentX = 0
       }
      },
      currentTime (cur, old) {
        if (cur >= this.limitTime) {
          this.audioPause()
          this.stop = true
          // this.playRemind()
          // if (~~this.$route.query.type === 0) {
          //   if (!sessionStorage.userInfo) {
          //     this.dialogConent = {
          //       title: ' 试听结束<br/> 想继续查',
          //       left: '返回',
          //       right: '立即登录'
          //     }
          //   }
          //   this.showDialog = true
          // }
        } else {
          this.stop = false
        }
      },

      'state.isPlaying' (cur, old) {
        this.$emit('statusChanged', cur)
      },

      computedCurrentAudioIndex (cur, old) {
        return this.audioData.audioUrl
      }
    },

  computed: {
    computedCurrentTime() {
      return this.formatTime(
        this.state.isTouching
          ? this.computedCurrentProcessRate * this.activeAudio.audioDuration
          : this.currentTime
      )
    },

    computedCurrentTime() {
      return this.formatTime(
        this.state.isTouching
          ? this.computedCurrentProcessRate * this.activeAudio.audioDuration
          : this.currentTime
      )
    },

    computedDuration() {
      return this.formatTime(this.activeAudio.audioDuration)
    },

    computedProgress() {
      if (this.state.isTouching) {
        return this.computedCurrentProcessRate * 100
      }

      if (this.currentTime && this.activeAudio.audioDuration) {
        return this.currentTime / this.$refs.audio.duration * 100
      } else {
        return 0
      }
    },

    computedCurrentProcessRate() {
      const {offsetLeft, offsetWidth} = this.$refs.process
      return (this.currentX - offsetLeft) / offsetWidth
    }
  },


    methods: {
       cancelBtn () {
         this.currentTime = 0
         this.$refs.audio.currentTime = 0
          setTimeout (() => {
              this.showDialog = false
          }, 200)
      },
      gotomanuscript() {
        if(this.$router.currentRoute.query.type == 0) {
          Toast('试听不可查看文稿')
          return false
        } else {
          // const uid = this.$router.currentRoute.query.uid
          // const fid = this.$router.currentRoute.query.pid
          const contentHtml = this.audioData.contentHtml
          sessionStorage.contentHtml = contentHtml
          const title = this.contentHtmlTitle
          this.$router.push({path:'manuscript', query:{title}})
        }
      },
      zan(){
        const data = {
          uid: this.$router.currentRoute.query.uid,
          fid: this.$router.currentRoute.query.pid,
          type: 1
        }
        bookPraise({data}).then((res) => {
          if(res.data.code == 0) {
            this.getZanNum()
          }
        })
      },
      getZanNum() {
        const data = {
          uid: this.$router.currentRoute.query.uid,
          fid: this.$router.currentRoute.query.pid,
          type: 1
        }
        bookPraiseNumber({data}).then((res) => {
          if(res.data.code == 0) {
            this.zanNum = res.data.result
          }
        })
      },
      sureBtn () {
        const userinfo = sessionStorage.userInfo
          if(!!userinfo) {
            this.$router.push({path: 'confirOrder', query: {uid: this.$router.currentRoute.query.uid}})
          } else {
            this.$router.push({path:'mobillogin',query: {id: this.$router.currentRoute.query.pid, from: 'detail'}})
          }
      },
      formatTime(time) {
        const {floor} = Math
        let s, m, h
        s = m = h = 0
        if (time) {
          s = floor(time % 60)
          m = floor(time / 60)
          h = floor(time / (60 ** 2))
        }
        const s_string = s < 10 ? '0' + s : s.toString()
        const m_string = m < 10 ? '0' + m : m.toString()
        if (h === 0) {
          return [m_string, s_string].join(':')
        } else {
          const h_string = h < 10 ? '0' + h : h.toString()
          return [h_string, m_string, s_string].join(':')
        }
      },

      changeCurrentTime(second) {
        if (this.stop) {
          return false
        }

        this.$refs.audio.currentTime += second
        if (this.$refs.audio.currentTime > 0) {
          this.currentTime = this.$refs.audio.currentTime
        }
      },

      changeCurrentAudioIndex(change) {
        this.currentAudioIndex = // 这是1种循环
          (this.currentAudioIndex + change + this.audioData.length) % this.audioData.length
        this.state.isPlaying = this.autoPlay
      },

      startAudioWatch() {
        const that = this
        that.stopAudioWatch()
        that.currentTimeWatcher = setInterval(() => {
          if (that.$refs.audio) {
            that.currentTime = that.$refs.audio.currentTime
          }
        }, 300)
      },

      stopAudioWatch() {
        clearInterval(this.currentTimeWatcher)
      },

      audioPlay() {
        if (this.stop) {
          return false
        }

        this.$refs.audio.play()
        this.state.isPlaying = true
        this.startAudioWatch()
      },

      playRemind() {
        this.$refs.remind.play()
        var audio = document.getElementById('remind')
        if (window.WeixinJSBridge) {
          WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
              audio.play()
          }, false)
        } else {
          document.addEventListener('WeixinJSBridgeReady', function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                audio.play()
            })
          }, false)
        }
        audio.play()
        return false
      },

      stopPlayRemind() {
        this.$refs.remind.pause()
      },

      audioPause() {
        this.$refs.audio.pause()
        this.state.isPlaying = false
        this.stopAudioWatch()
      },

      audioToggle() {
        if (this.stop) {
          return false
        }

        // this.stopPlayRemind()
        this.state.isPlaying && (this.currentTime <= this.limitTime) ? this.audioPause() : this.audioPlay()
      },

      onAudioEnd() {
        this.changeCurrentAudioIndex(1)
        this.state.isPlaying = this.autoPlay
      },

      onProcess(x) {
        // if (this.stop) {
        //   return false
        // }

        const {offsetLeft, offsetWidth} = this.$refs.process
        if (offsetLeft <= x && x <= offsetLeft + offsetWidth) {
          const {audio} = this.$refs
          const rate = (x - offsetLeft) / offsetWidth
          this.currentTime = audio.currentTime = audio.duration * rate
        }
      },

      onProcessTouchStart(e) {
        // if (this.stop) {
        //   return false
        // }

        this.currentX = e.changedTouches[0].clientX
        this.state.isTouching = true
      },

      onProcessTouchMove(e) {
        //  if (this.stop) {
        //   return false
        // }

        const x = e.changedTouches[0].clientX
        const {offsetLeft, offsetWidth} = this.$refs.process
        if (offsetLeft <= x && x <= offsetLeft + offsetWidth) {
          this.currentX = x
        }
      },

      onProcessTouchEnd(e) {
        // if (this.stop) {
        //   return false
        // }

        this.state.isTouching = false
        this.onProcess(e.changedTouches[0].clientX)
      },
    },

     mounted() {
       const that = this
       that.startAudioWatch()
    },

    destroyed() {
      clearInterval(this.currentTimeWatcher)
    },
}
</script>

<style lang="less" scoped="scoped">
.process-bar {
   padding: 0 0.6rem;
   margin-bottom: 0.6rem;
   margin-top: 0.5rem;

  .process-lines {
    position: relative;
    margin: 0.1rem 0;

    .total-line {
      height: 1px;
      background-color: #ccc;
      z-index: 1;
    }

    .current-line {
      position: absolute;
      left: 0;
      top: 0;
      height: 1px;
      background-color: #363636;
      z-index: 3;
      width: 10%;

      &::before {
        content: '';
        position: absolute;
        right:  0;
        top:  0;
        transform : translate(50%, -50%);
        width:  0.28rem;
        height : 0.28rem;
        background-color: #b2b2b2;
        border-radius : 50%;
        animation:  breath ease-in-out 3s infinite;
      }

      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        width: 0.18rem;
        height: 0.18rem;
        background-color: #363636;
        border-radius: 50%;
        transform: translate(50%, -50%);
      }
      .loading {
        position :absolute;
        transform :translate(50%, -50%) rotate(0turn);
        z-index : 10;
        // background :url("../../assets/img/loading.svg") center center no-repeat;
        background-size :70%;
        right : 0;
        top: 0;
        border-radius :50%;
        width :0.18rem;
        height: 0.18rem;
        animation: rotate linear 5s infinite;
      }
    }
  }

  .data {
    color: #707070;
    font-size: 0.2rem;
    display: flex;
    flex-direction :row;
    justify-content :space-between;
    align-items: center;
    overflow: hidden
  }
}

.control-operation {
}

.control-bar {
  display: flex;
  justify-content: center;
  justify-items: center;
  width: 100%;
  box-sizing: border-box;
  padding: 0 0.3rem 0.3rem;

  .pre-seconds,
  .next-seconds {
    width: 0.8rem;
    height: 0.8rem;
  }

  .pre-seconds {
    background: url("../assets/img/15-pre.png") no-repeat center center;
    background-size: 0.4rem  0.4rem;
  }

  .next-seconds {
    background: url("../assets/img/15-next.png") no-repeat center center;
    background-size: 0.4rem  0.4rem;
  }

  .btn-pre-seconds,
  .btn-next-seconds {
    display: block;
    width: 100%;
    height: 100%;
  }

  .btn-play {
    display: block;
    // border: 0.04rem solid #282828;
    // padding: 0.2rem;
    border-radius:50%;
    width: 0.8rem;
    height: 0.8rem;
    margin: 0 0.3rem;

    background: url('../assets/img/audio-pause.png') center center no-repeat;
    background-size: 100%;

    &.isPlaying {
      background: url('../assets/img/audio-play.png') center center no-repeat;
       background-size: 100%;

    }
  }
}
</style>
